Repository navigation
feat(cli): improve prisma postgres create db setup - #558
Conversation
WalkthroughAdds a repository-wide Cursor rules file and refactors the Prisma Postgres CLI setup to use a JSON/region-driven create-db flow with a spinner, structured output parsing, and optional CLAIM_URL persistence and logging. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor U as User
participant C as CLI Prisma Postgres Setup
participant R as Region Selector
participant D as create-db@latest
participant P as JSON Parser
participant E as Env Writer
participant L as Logger
U->>C: Run setup
C->>R: Prompt for region
R-->>C: Selected region
C->>D: Execute create-db --json --region <region>
activate C
D-->>C: JSON stdout (CreateDbResponse)
C->>P: Parse JSON output
alt Parse OK
P-->>C: connectionString(s), claimUrl?
C->>C: Choose DB URL (direct vs standard) based on ORM
opt claimUrl present
C->>E: Write CLAIM_URL to apps/server/.env
E-->>C: Done
end
C->>L: Log success and optional claim URL info
else Parse error
P-->>C: Error
C->>L: Log parse/creation error
end
deactivate C
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
✨ Finishing Touches
🧪 Generate unit tests
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
apps/cli/src/helpers/database-providers/prisma-postgres-setup.ts (1)
174-186: Remove dotenv injection; violates repo guidelines (Bun auto-loads .env)Guidelines: “Do not use dotenv; Bun auto-loads .env”. Drop the import insertion and its call.
-async function addDotenvImportToPrismaConfig(projectDir: string) { - try { - const prismaConfigPath = path.join( - projectDir, - "apps/server/prisma.config.ts", - ); - let content = await fs.readFile(prismaConfigPath, "utf8"); - content = `import "dotenv/config";\n${content}`; - await fs.writeFile(prismaConfigPath, content); - } catch (_error) { - consola.error("Failed to update prisma.config.ts"); - } -} @@ - if (orm === "prisma") { - await addDotenvImportToPrismaConfig(projectDir); - await addPrismaAccelerateExtension(serverDir); - } + if (orm === "prisma") { + await addPrismaAccelerateExtension(serverDir); + }Also applies to: 283-286
🧹 Nitpick comments (10)
.cursor/rules/better-t-stack-repo.mdc (2)
6-8: Tighten wording and fix typos in rules listClarify and correct grammar to avoid ambiguity.
- use normal function syntax for functions do not use arrow functions + use normal function syntax for functions (do not use arrow functions) - use type syntax, dont use interface syntax for types + use type syntax; don't use interface syntax for types
5-5: Be explicit about “functional programming” scopeIf this is an enforcement signal for Cursor, consider clarifying “prefer functional style (pure functions, immutability where practical)” to reduce subjective interpretations.
apps/cli/src/helpers/database-providers/prisma-postgres-setup.ts (8)
60-76: Stop spinner after successful JSON parse; show failure on parse errorCurrently it prints “success” even when JSON parsing fails.
- s.start("Creating Prisma Postgres database..."); + s.start("Creating Prisma Postgres database..."); @@ - s.stop("Database created successfully!"); - - let createDbResponse: CreateDbResponse; - try { - createDbResponse = JSON.parse(stdout) as CreateDbResponse; - } catch { - consola.error("Failed to parse create-db response"); - return null; - } + let createDbResponse: CreateDbResponse; + try { + createDbResponse = JSON.parse(stdout) as CreateDbResponse; + s.stop("Database created successfully!"); + } catch { + s.stop("Failed to create database"); + consola.error("Failed to parse create-db response"); + return null; + }
28-35: Literal-type AVAILABLE_REGIONS and type-safe select valueStrengthen types; avoid any/string leaks.
-const AVAILABLE_REGIONS = [ +const AVAILABLE_REGIONS = [ { value: "ap-southeast-1", label: "Asia Pacific (Singapore)" }, { value: "ap-northeast-1", label: "Asia Pacific (Tokyo)" }, { value: "eu-central-1", label: "Europe (Frankfurt)" }, { value: "eu-west-3", label: "Europe (Paris)" }, { value: "us-east-1", label: "US East (N. Virginia)" }, { value: "us-west-1", label: "US West (N. California)" }, -]; +] as const; @@ -const selectedRegion = await select({ +type Region = typeof AVAILABLE_REGIONS[number]["value"]; +const selectedRegion = await select<Region>({ message: "Select your preferred region:", options: AVAILABLE_REGIONS, initialValue: "ap-southeast-1", });Also applies to: 47-51
18-26: Loosen CreateDbResponse for resilience and future-proofingSome fields may be absent depending on CLI/version. Make optional where safe.
type CreateDbResponse = { - connectionString: string; - directConnectionString: string; - claimUrl: string; - deletionDate: string; - region: string; - name: string; - projectId: string; + connectionString?: string; + directConnectionString?: string; + claimUrl?: string; + deletionDate?: string; + region?: string; + name?: string; + projectId?: string; };Also guard when deriving databaseUrl (e.g., throw if missing).
78-82: Guard against missing connection stringsAvoid undefined DATABASE_URL on schema changes.
-const databaseUrl = - orm === "drizzle" - ? createDbResponse.directConnectionString - : createDbResponse.connectionString; +const databaseUrl = + orm === "drizzle" + ? createDbResponse.directConnectionString + : createDbResponse.connectionString; +if (!databaseUrl) { + consola.error("create-db response missing connection string"); + return null; +}
124-131: Validation may be too strict for future Prisma URLsIf Prisma changes the scheme, this will block valid inputs. Consider a looser validator that still ensures Prisma Accelerate usage.
- if (!value.startsWith("prisma+postgres://")) { - return "URL should start with prisma+postgres://"; - } + const valid = /^prisma\+postgres:\/\//.test(value); + if (!valid) return "Expected Prisma Accelerate URL (prisma+postgres://...)";
199-215: Avoid overwriting files; make replacement more robust
- Only create prisma/index.ts if absent.
- Use regex to replace PrismaClient construction to handle formatting variants.
-const prismaIndexPath = path.join(serverDir, "prisma/index.ts"); -const prismaIndexContent = ` +const prismaIndexPath = path.join(serverDir, "prisma/index.ts"); +const prismaIndexContent = ` import { PrismaClient } from "./generated/client"; import { withAccelerate } from "@prisma/extension-accelerate"; const prisma = new PrismaClient().$extends(withAccelerate()); export default prisma; `; -await fs.writeFile(prismaIndexPath, prismaIndexContent.trim()); +if (!(await fs.pathExists(prismaIndexPath))) { + await fs.writeFile(prismaIndexPath, prismaIndexContent.trim()); +} @@ -dbFileContent = dbFileContent.replace( - "export const db = new PrismaClient();", - "export const db = new PrismaClient().$extends(withAccelerate());", -); +dbFileContent = dbFileContent.replace( + /export\s+const\s+db\s*=\s*new\s+PrismaClient\(\)\s*;/, + "export const db = new PrismaClient().$extends(withAccelerate());", +);Also applies to: 217-231
296-298: Avoid echoing sensitive claim URLs to consoleTreat claimUrl as sensitive. Point users to .env instead of printing the value.
-if (prismaConfig.claimUrl) { - log.info(pc.blue(`Claim URL saved to .env: ${prismaConfig.claimUrl}`)); -} +if (prismaConfig.claimUrl) { + log.info(pc.blue("Claim URL saved to apps/server/.env (CLAIM_URL).")); +}
149-166: CLAIM_URL isn’t consumed
Defined only in apps/cli/src/helpers/database-providers/prisma-postgres-setup.ts (lines 160–166) and never referenced elsewhere; remove it from the generated .env to avoid unnecessary secrets.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
.cursor/rules/better-t-stack-repo.mdc(1 hunks)apps/cli/src/helpers/database-providers/prisma-postgres-setup.ts(4 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/convex_rules.mdc)
**/*.{ts,tsx}: Use Id from './_generated/dataModel' to type document ids (e.g., Id<'users'>)
Ensure Record key/value types align with validators (e.g., v.record(v.id('users'), v.string()) => Record<Id<'users'>, string>)
Be strict with types for document ids; prefer Id<'table'> over string
Use 'as const' for string literals in discriminated unions
When using Array and Record types, declare with explicit generic types (e.g., const arr: Array = ...)
Files:
apps/cli/src/helpers/database-providers/prisma-postgres-setup.ts
**/*.{js,jsx,ts,tsx,mjs,cjs}
📄 CodeRabbit inference engine (.cursor/rules/use-bun-instead-of-node-vite-npm-pnpm.mdc)
**/*.{js,jsx,ts,tsx,mjs,cjs}: Do not use dotenv; Bun auto-loads .env
UseBun.serve()for HTTP/WebSockets; do not useexpress
Usebun:sqlitefor SQLite; do not usebetter-sqlite3
UseBun.redisfor Redis; do not useioredis
UseBun.sqlfor Postgres; do not usepgorpostgres.js
Use built-inWebSocket; do not usews
PreferBun.fileovernode:fsreadFile/writeFile
UseBun.$instead ofexecafor shelling out
Files:
apps/cli/src/helpers/database-providers/prisma-postgres-setup.ts
🧠 Learnings (1)
📚 Learning: 2025-08-24T18:00:39.152Z
Learnt from: CR
PR: AmanVarshney01/create-better-t-stack#0
File: .cursor/rules/convex_rules.mdc:0-0
Timestamp: 2025-08-24T18:00:39.152Z
Learning: Applies to convex/**/*.ts : Always use the new Convex function syntax (query/mutation/action/internal*) with args/returns/handler
Applied to files:
.cursor/rules/better-t-stack-repo.mdc
🧬 Code graph analysis (1)
apps/cli/src/helpers/database-providers/prisma-postgres-setup.ts (2)
apps/cli/src/types.ts (2)
PackageManager(64-64)ORM(11-11)apps/cli/src/utils/package-runner.ts (1)
getPackageExecutionCommand(11-23)
| import { isCancel, log, select, text } from "@clack/prompts"; | ||
| import { isCancel, log, select, spinner, text } from "@clack/prompts"; | ||
| import { consola } from "consola"; | ||
| import { execa } from "execa"; |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Use Bun.$ for subprocesses instead of execa
Guidelines require Bun.$. Replace execa calls accordingly.
-import { execa } from "execa";
+import { $ } from "bun";
@@
- const { stdout } = await execa(createDbCommand, {
- cwd: serverDir,
- shell: true,
- });
+ const stdout = await $`bash -lc "cd ${serverDir} && ${createDbCommand}"`.text();
@@
- await execa(prismaInitCommand, {
- cwd: serverDir,
- stdio: "inherit",
- shell: true,
- });
+ await $`bash -lc "cd ${serverDir} && ${prismaInitCommand}"`;If you prefer avoiding bash -lc, split args and use $ with a cwd-scoped variant.
Also applies to: 63-66, 112-116
🤖 Prompt for AI Agents
In apps/cli/src/helpers/database-providers/prisma-postgres-setup.ts around line
4 (also apply changes at lines 63-66 and 112-116), replace usage of execa
imports and calls with Bun.$ subprocess calls; remove the import of execa and
convert each execa invocation to Bun.$ by passing the command and args without
relying on "bash -lc" (or if you must use a shell, use Bun.spawn or Bun.$ with
proper shell flag), and prefer passing argv as separate elements and using the
cwd option when needed to avoid shell quoting issues; ensure exit codes/errors
are handled similarly (await the Bun.$ promise or catch errors) so behavior and
logging remain consistent.
Summary by CodeRabbit
New Features
Style
Chores